﻿@{
    Layout = "";
}
@using System.Text.Encodings.Web
@model DiscountRules.Standard.Models.RequirementOneProductModel

<script>
    $(document).ready(function () {
        $('#saveHasOneProductrequirement@(Model.RequirementId)').click(function () {
            var productIds = $("#@Html.IdFor(model => model.Products)").val();
            var discountId = '@Model.DiscountId';
            var requirementId = '@Model.RequirementId';

            var postData = {
                discountId: discountId,
                discountRequirementId: requirementId,
                productIds: productIds
            };
            addAntiForgeryToken(postData);

            $.ajax({
                cache:false,
                type: "POST",
                url: "@Url.Action("Configure", "HasOneProduct")",
                data: postData,
                success: function (data) {
                    $('#pnl-save-requirement-result@(Model.RequirementId)').fadeIn("slow").delay(1000).fadeOut("slow");
                    //notify parent if it's a new requirement
                    @if (string.IsNullOrEmpty(Model.RequirementId))
                    {
                        <text>$("#discountRequirementContainer").trigger('grandnewdiscountruleadded', [data.NewRequirementId]);</text>
                    }
                },
                error:function (xhr, ajaxOptions, thrownError){
                    alert('@Html.Raw(JavaScriptEncoder.Default.Encode(Loc["admin.marketing.Discounts.Requirements.FailedToSave"]))');
                }
            });
        });
    });
</script>

<div class="form-body">
    <admin-label asp-for="Products"/>
    <div class="col-md-8 col-sm-8">
        <admin-input asp-for="Products"/>
        <label class="control-label" style="text-align:left" id="discountrequirement-product-names@(Model.RequirementId)"></label>
        <div class="group-btn btn-group-devided margin-top-10">
            <input type="button" id="saveHasOneProductrequirement@(Model.RequirementId)" class="btn default" value="@Loc["Admin.Common.Save"]"/>
            <a id="btnAddNewDiscountRequirementProduct@(Model.RequirementId)" href="@(Url.RouteUrl("Plugin.DiscountRules.HasOneProduct.ProductAddPopup", new { btnId = "btnRefreshDiscountRequirementProducts" + Model.RequirementId, productIdsInput = Html.IdFor(model => model.Products) }))" class="btn default">
                @Loc["Plugins.DiscountRules.HasOneProduct.Fields.Products.AddNew"]
            </a>
        </div>

        <div id="pnl-save-requirement-result@(Model.RequirementId)" style="display:none;">@Loc["admin.marketing.Discounts.Requirements.Saved"]</div>
        <span id="discountrequirement-products-check-progress@(Model.RequirementId)" style="display: none;" class="please-wait">@Loc["Common.Wait..."]</span>

        <input type="submit" id="btnRefreshDiscountRequirementProducts@(Model.RequirementId)" style="display: none"/>
    </div>

    <script>
        $(document).ready(function () {
            $('#btnAddNewDiscountRequirementProduct@(Model.RequirementId)').magnificPopup({
                        type: 'ajax',
                        settings: { cache: false, async: false },
                        midClick: true,
                        callbacks: {
                            parseAjax: function (mfpResponse) {
                                mfpResponse.data = $('<div></div>').html(mfpResponse.data);
                            },
                            ajaxContentAdded: function () {
                                $('.mfp-wrap').removeAttr('tabindex');
                            }
                        }
                    });
            $('#btnRefreshDiscountRequirementProducts@(Model.RequirementId)').click(function () {
                //refresh product list
                loadDiscountRequirementProductFriendlyNames@(Model.RequirementId)();

                //return false to don't reload a page
                return false;
            });

            loadDiscountRequirementProductFriendlyNames@(Model.RequirementId)();

            $('#@Html.IdFor(model => model.Products)')
                .data('timeout', null)
                .keyup(function () {
                    clearTimeout($(this).data('timeout'));
                    //one second timeout
                    $(this).data('timeout', setTimeout(loadDiscountRequirementProductFriendlyNames@(Model.RequirementId), 1000));
                });
        });

        function loadDiscountRequirementProductFriendlyNames@(Model.RequirementId)() {
            var inputValue = $('#@Html.IdFor(model => model.Products)').val();
            if (inputValue) {
                //load friendly names
                $('#discountrequirement-products-check-progress@(Model.RequirementId)').show();

                var postData = {
                    productIds: inputValue
                };
                addAntiForgeryToken(postData);

                $.ajax({
                    cache: false,
                    type: 'POST',
                    url: '@Url.RouteUrl("Plugin.DiscountRules.HasOneProduct.LoadProductFriendlyNames")',
                    data: postData,
                    dataType: 'json',
                    success: function (data) {
                        $('#discountrequirement-products-check-progress@(Model.RequirementId)').hide();
                        $('#discountrequirement-product-names@(Model.RequirementId)').text(data.Text);
                    },
                    failure: function () {
                        $('#discountrequirement-products-check-progress@(Model.RequirementId)').hide();
                        $('#discountrequirement-product-names@(Model.RequirementId)').text('');
                    }
                });
            } else {
                $('#discountrequirement-product-names@(Model.RequirementId)').text('');
            }
        }
    </script>
</div>